/*
 * 文  件   名: SigninWidget.java
 * 版         本 : docrepository-console(Anttribe). All rights reserved.
 * 描         述 : <描述>
 * 修   改  人: zhaoyong
 * 修改时间: 2014年9月30日
 */
package org.anttribe.docrepository.console.signin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.anttribe.docrepository.common.UnifyException;
import org.anttribe.docrepository.common.constants.Keys;
import org.anttribe.docrepository.console.signin.vo.SigninVo;
import org.anttribe.docrepository.user.domain.UserInfo;
import org.anttribe.docrepository.user.manager.UserInfoManager;
import org.anttribe.saturn.common.utils.ObjectUtils;
import org.anttribe.saturn.runtime.stereotype.Widget;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录Widget
 * 
 * @author zhaoyong
 * @version 2014年9月30日
 */
@Widget(name = "Signin")
@RequestMapping("/signin")
public class SigninWidget
{
    /**
     * LOGGER
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SigninWidget.class);
    
    /**
     * userInfoManager
     */
    @Autowired
    private UserInfoManager userInfoManager;
    
    /**
     * 登录index
     * 
     * @return String
     */
    @RequestMapping("/index")
    public String doIndex()
    {
        return "signin/signin";
    }
    
    /**
     * 实现登录逻辑
     * 
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param httpSession HttpSession
     * @param signinVo signinVo
     * @return ModelAndView
     */
    @RequestMapping("/doSignin")
    public ModelAndView doSignin(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession,
        @ModelAttribute SigninVo signinVo)
    {
        ModelAndView mv = new ModelAndView();
        
        UserInfo userInfo = (UserInfo)httpSession.getAttribute(Keys.USER_SESSION);
        if (ObjectUtils.isNullOrNone(userInfo))
        {
            try
            {
                // 登录逻辑
                userInfo = userInfoManager.login(signinVo.getUserAccount(), signinVo.getPassword());
            }
            catch (UnifyException e)
            {
                LOGGER.warn("While signining, get error: {}", e.getErrorNo());
                
                mv.addObject("errorNo", e.getErrorNo());
                mv.setViewName("/signin");
                return mv;
            }
        }
        
        LOGGER.debug("User has signin successful, userinfo {}", userInfo);
        
        // 将用户信息保存到session中
        httpSession.setAttribute(Keys.USER_SESSION, userInfo);
        mv.addObject("userInfo", userInfo);
        mv.setViewName("index");
        return mv;
    }
}